clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"
cd "${code}/tba_elig"

use "${temp}/gse_id-harp-cleaned.dta", clear

do _HARP-sampleselection // sample selection
do _HARP-spec

keep if year(dofm(orig_ym)) >= 2012
su credit_scorecore_b, d
keep if credit_scorecore_b <= `r(p50)'

// prepayment
merge 1:1 id_loan_harp using "${cached}/harp-performance-combined.dta", keep(matched master)
drop _merge

gen max_age = max_ym - orig_ym
foreach n of numlist 36 60 {
	rename current_upb`n' curr_rpb`n'
	replace curr_rpb`n' = 0 if curr_rpb`n' == . & prepaid == 1 & last_age+1 <= `n'  & max_age > `n'+1
	replace curr_rpb`n' = curr_rpb`n' / orig_amount

	gen pp`n' = (curr_rpb`n' == 0) if curr_rpb`n' ~= . 
}



// winsorize
qui su orig_rt, d
replace orig_rt = . if inrange(orig_rt, `r(p1)', `r(p99)')==0


foreach x in homevalue prin_bal_amount orig_amount {
	replace `x' = `x'/1000
}

eststo clear
eststo: estpost su hi_ltvprev hi_ltv pp36 ltvprev oltv homevalue prin_bal_amount orig_amount orig_rt credit_scorecore_b , d

label var hi_ltvprev "Share of loans with $ MaxLTV$ > 105"
label var hi_ltv "Share of loans with actual LTV > 105"
label var notba "Share of loans in TBA-ineligible MBS"
label var ltvprev "$ MaxLTV$"
label var oltv "Actual LTV"
label var homevalue "Appraisal value (\textdollar 1,000)"
label var prin_bal_amount "Ending balance of previous loan (\textdollar 1,000)"
label var orig_amount "Loan size (\textdollar 1,000)"
label var orig_rt "Mortgage rate (\%)"
label var credit_scorecore_b "Credit score"
label var pp36 "Share of loans paid off by loan age 36 months"
*label var pp60 "Share of loans paid off by loan age 60 months"

global keepvar "keep(ltvprev oltv homevalue prin_bal_amount orig_amount orig_rt credit_scorecore_b)"

esttab using "${table}/harp-sumstat.tex", label replace nomtitle nonumber /// 
  stats(N, fmt(%9.0fc) label("N. Obs."))  ///
  cell("mean(fmt(%11.2fc)) min($keepvar) p25($keepvar) p50($keepvar) p75($keepvar) max($keepvar)") collabels("Mean" "Min" "p25" "Median" "p75" "Max")
